// 封装购物车模块

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getCart, deleteCartAll, deleteCartById, updateCartQuantity } from '@/apis/cart'

export const useCartStore = defineStore('cart', () => {
  // 状态
  const cartItems = ref([])
  const selectedItems = ref([])
  const selectAll = ref(false)
  const Load = ref(false)

  // 计算属性
  const totalItems = computed(() => {
    return cartItems.value.reduce((sum, item) => sum + item.quantity, 0)
  })

  const totalPrice = computed(() => {
    return cartItems.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
  })

  const selectedTotalPrice = computed(() => {
    return selectedItems.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
  })

  // 核心方法
  const setCartItems = (items) => {
    cartItems.value = items
  }

  const setLoading = (loading) => {
    Load.value = loading
  }

  const handleSelectionChange = (val) => {
    selectedItems.value = val
    selectAll.value = val.length === cartItems.value.length && cartItems.value.length > 0
  }

  // API 相关方法
  const fetchCartItems = async (userId) => {
    setLoading(true)
    try {
      const res = await getCart({
        userId,
        pageNum: 1,
        pageSize: 5,
      })
      if (res.code === '0') {
        setCartItems(res.data.records)
      }
      return res
    } catch (error) {
      throw error
    } finally {
      setLoading(false)
    }
  }

  const updateItemQuantity = async (id, quantity) => {
    try {
      const res = await updateCartQuantity(id, quantity)
      return res
    } catch (error) {
      throw error
    }
  }

  const deleteCartItem = async (id) => {
    try {
      const res = await deleteCartById(id)
      return res
    } catch (error) {
      throw error
    }
  }

  const clearAllItems = async () => {
    try {
      const res = await deleteCartAll()
      return res
    } catch (error) {
      throw error
    }
  }

  return {
    // 状态
    cartItems,
    selectedItems,
    selectAll,
    Load,
    // 计算属性
    totalItems,
    totalPrice,
    selectedTotalPrice,
    // 方法
    setCartItems,
    setLoading,
    handleSelectionChange,
    fetchCartItems,
    updateItemQuantity,
    deleteCartItem,
    clearAllItems
  }
})